/* 商户：商城详情页 */
import Imagelocation from '@/components/Imagelocation';
import Search from '@/components/Search';
import { sourceUrl } from '@/config';
import pStarDown from '@/mainSubPack/images/shoppingMall/starDown.png';
import pStarUp from '@/mainSubPack/images/shoppingMall/starUp.png';
import pGouwuche from '@/mainSubPack/images/takeOutShop/gouwuche.png';
import { debounce } from '@/utils/helper';
import utils from '@/utils/index';
import { Image, ScrollView, Text, View } from '@tarojs/components';
import Taro, { useDidShow, useRouter } from '@tarojs/taro';
import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import ProductTitle from '@/components/product/ProductTitle';
import EmptyProduct from '../../components/EmptyProduct';
import { ProductClassification } from './productClassification';
import Tabs from './tabs';

const ProductClassificationValue = 5;
import './index.scss';

const sortList = [
  { value: 1, label: '新品' },
  { value: 2, label: '销量' },
  { value: 3, label: '价格', switch: true, switchValue: 4 },
  { value: ProductClassificationValue, label: '商品分类' },
];

const goCartPage = () => {
  if (!utils.getToken()) {
    Taro.navigateTo({
      url: '/pages/other/login/index',
    });
    return;
  }
  let url = '/pages/mainPages/cartSin/index';
  Taro.navigateTo({
    url,
  });
};

const Theme = ({ themeGoods = [], dispatch }) => {
  return (
    <View className="themeContent">
      {themeGoods.length > 0 &&
        themeGoods.map((good, index) => (
          <View
            className="goodInfo"
            key={'theme' + good.id + '_' + index}
            onClick={() => utils.goGoodDetail(good, dispatch)}
          >
            <View className="goodIcon">
              <Image
                className="gIcon"
                src={good.url?.indexOf('http') === 0 ? good.url : sourceUrl + good.url}
              />
            </View>
            <View className="goodBase">
              {/* <Text className="goodName">{good.title}</Text> */}
              <ProductTitle product={good} />
              <Text className="goodPrice customePageStyle">¥{good.price}</Text>
              <Text className="goodSale">已售卖{good.saleNum || 0}件</Text>
            </View>
          </View>
        ))}
    </View>
  );
};

const Products = ({ dispatch, recProductList, recProductFinished }) => {
  return (
    <>
      <Theme themeGoods={recProductList} dispatch={dispatch} />
      {recProductFinished && recProductList.length > 8 && (
        <View className="end">- 我是有底线的 -</View>
      )}

      {recProductFinished && recProductList.length === 0 && (
        <EmptyProduct
          txt="该商户暂无商品哟～"
          style={{
            height: utils.getCalcHeight('100vh', 232, 120),
          }}
        />
      )}
    </>
  );
};

const ShoppingMallPage = ({
  dispatch,
  recProductList = [],
  recProductFinished = false,
  productNumInCart = null,
  productGroups,
}) => {
  const [currentTab, setCurrentTab] = useState(1);
  const [shopBaseInfo, setShopBaseInfo] = useState({});

  const router = useRouter();
  const { params = {} } = router;
  const merchantId = params.merchantId;
  const orgId = params.orgId;

  const handleTabChanged = (index) => {
    if (sortList[index].switch) {
      setCurrentTab(
        currentTab == sortList[index].value ? sortList[index].switchValue : sortList[index].value,
      );
    } else {
      setCurrentTab(sortList[index].value);
    }
  };

  const showNextPageData = debounce(() => {
    getRecommendProduct();
  }, 1200);

  const getShopBaseInfo = () => {
    dispatch({
      type: 'takeOut/getActivityOrgInfoModel',
      payload: { orgId },
    }).then((data) => {
      setShopBaseInfo({ ...data });
    });
  };

  const getRecommendProduct = () => {
    dispatch({
      type: 'productList/getRecommendByOrg',
      payload: { orgId, pageSize: 20, sort: currentTab },
    });
  };

  const getProductTotalNum = () => {
    dispatch({
      type: 'productList/getProductTotalNum',
      payload: { merchantId, orgId, type: 1 },
    });
  };

  const handleSearch = (v) => {
    if (!v) {
      Taro.showToast({
        title: '请输入关键字',
        duration: 2000,
        icon: 'none',
      });
      return;
    }

    Taro.navigateTo({
      url: `/mainSubPack/shopProductFilter/index?groupId=${merchantId}&orgId=${orgId}&groupName=${encodeURIComponent(
        shopBaseInfo?.name,
      )}&keywords=${encodeURIComponent(v)}`,
    });
  };

  useEffect(() => {
    if (orgId !== null) {
      getShopBaseInfo();
    }
    return () => {
      dispatch({
        type: 'productList/setProductTotalNum',
        payload: { productNumInCart: null },
      });
    };
  }, []);

  useEffect(() => {
    if (!orgId) {
      return;
    }

    // 商品分组, 请求其它接口
    if (currentTab === ProductClassificationValue) {
      return;
    }

    getRecommendProduct();
  }, [currentTab]);

  useDidShow(() => {
    if (orgId !== null && merchantId !== null && utils.getToken()) {
      getProductTotalNum();
    }
  });

  // 商城商品分组列表
  useEffect(() => {
    if (!merchantId) {
      return;
    }

    dispatch({
      type: 'productList/fetchProductGroups',
      payload: merchantId,
    });
  }, [merchantId]);

  return (
    <ScrollView
      className="ShoppingMallPage"
      scrollY
      lowerThreshold={240}
      onScrollToLower={showNextPageData}
    >
      <View className="shopBaseInfo">
        <Imagelocation className="left" src={shopBaseInfo?.logo} type="shop" />

        <View className="right">
          <View className="shopName">{shopBaseInfo.name}</View>
          <View className="shopStastic">
            <Text className="grade">{shopBaseInfo.grade}</Text>
            <View className="start">
              <View className="backL">
                <Image className="sIcon" src={pStarDown} />
              </View>
              <View className="faceL" style={{ width: (shopBaseInfo.grade * 100) / 5 + '%' }}>
                <Image className="sIcon" src={pStarUp} />
              </View>
            </View>
            <Text className="saleNum">月售{shopBaseInfo.saleNum || 0}</Text>
          </View>
        </View>
      </View>

      <View className="product-search">
        <Search handleSearch={handleSearch} placeholder="店铺内搜索" />
      </View>

      <View className="sortType">
        <Tabs tabsList={sortList} getCurrentTab={handleTabChanged} />
      </View>

      {currentTab === ProductClassificationValue ? (
        <ProductClassification
          {...{
            productGroups,
            merchantId,
            orgId,
            shopName: shopBaseInfo.name,
          }}
        />
      ) : (
        <Products
          {...{
            dispatch,
            recProductList,
            recProductFinished,
          }}
        />
      )}

      <View className="cart">
        <Image className="gwcImg" src={pGouwuche} onClick={goCartPage} />
        {productNumInCart && productNumInCart > 0 && (
          <View
            className={[
              'gwcNum',
              productNumInCart > 9 && 'two',
              productNumInCart > 99 && 'three',
            ].join(' ')}
          >
            {productNumInCart > 99 ? '99+' : productNumInCart}
          </View>
        )}
      </View>
    </ScrollView>
  );
};

export default connect(({ productList }) => ({
  recProductList: productList.recShopProductList,
  recProductFinished: productList.recShopProductFinished,
  productNumInCart: productList.productNumInCart,
  productGroups: productList.productGroups,
}))(ShoppingMallPage);
